import java.io.*;
import java.util.ArrayList;

/**
 * Created by dllo on 18/4/16.
 */
public class IOUtis {

    public static final String FILE_NAME = "user.txt";  //psvs 字符串常量简写
    /*
    * 存储用户信息
    * @param user 要存储的用户信息
    *
    * */

    public static void saveUser(User user) {
        File file = new File(FILE_NAME);
        OutputStream os = null;     //使用FileOutputStream的父类创建

        try {
            if (!file.exists()) {      // 将if判断放到try - catch里面
                file.createNewFile();
            }
            os = new FileOutputStream(file,true);
            String userInfo = user.getUsername() + ":" + user.getPwd() + ";";
            os.write(userInfo.getBytes());   //写流


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll(os);
        }
    }


    // 取用户
    public static ArrayList<User> initUsers(){

        ArrayList<User> users = new ArrayList<>();
        File file = new File(FILE_NAME);
        if (!file.exists()){  //文件不存在,说明一个用户都没存
            return users;  //返回空
        }

        InputStream is = null;
        try {
            is = new FileInputStream(file);
            byte[] buff = new byte[1024];   // 边读边解析
            int pos = 0;
            StringBuilder builder = new StringBuilder();
            while ((pos = is.read(buff)) != -1){
                String s = new String(buff,0,pos);
                builder.append(s);
            }
            String data = builder.toString();

            String[] userInfos = data.split(";");
            for (String userInfo : userInfos) {
                String[] info = userInfo.split(":");
                User user = new User();
                user.setUsername(info[0]);
                user.setPwd(info[1]);
                users.add(user);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            closeAll(is);
        }

        return users;

    }


    // 封装关闭流的方法 ,有几个流需要关,就传几个参数,提高代码的整洁度
    public static void closeAll(Closeable... closeables) {  //Closeable 是有close方法的实现类

        if (closeables == null) {  //判断数组是否为空
            return;
        }

        for (Closeable closeable : closeables) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }


    }

}
